package com.mentalhealthplatform.teacherV2.controller;

import com.mentalhealthplatform.appModels.Message;
import com.mentalhealthplatform.appModels.MessageLike;
import com.mentalhealthplatform.appModels.Reply;
import com.mentalhealthplatform.exception.permssion.PermissionNotFoundException;
import com.mentalhealthplatform.global.rbac.jwt.JwtUtils;
import com.mentalhealthplatform.global.rbac.model.CustomUserDetails;
import com.mentalhealthplatform.teacherV2.dto.MessageDTO;
import com.mentalhealthplatform.teacherV2.dto.ReplyDTO;
import com.mentalhealthplatform.teacherV2.repository.MessageLikeRepository;
import com.mentalhealthplatform.teacherV2.service.MessageServiceV2;
import com.mentalhealthplatform.teacherV2.service.ReplyServiceV2;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v2/teacher/messages")
public class MessageControllerV2 {

    @Autowired
    private MessageServiceV2 messageService;

    @Autowired
    private ReplyServiceV2 replyService;

    @Autowired
    private MessageLikeRepository messageLikeRepository;

    @Autowired
    private JwtUtils jwtUtils;

    // 获取所有消息
    @GetMapping("/all")
    public ResponseEntity<List<MessageDTO>> getAllMessages() {
        List<Message> messages = messageService.findAll();
        List<MessageDTO> messageDTOs = messages.stream().map(this::convertToDTO).collect(Collectors.toList());
        return ResponseEntity.ok(messageDTOs);
    }

    // 回复指定消息
    @PostMapping("/{messageId}/reply")
    public ResponseEntity<ReplyDTO> replyToMessage(@PathVariable Long messageId, @RequestBody ReplyDTO replyDTO) {
        Optional<Message> messageOptional = messageService.findById(messageId);
        if (messageOptional.isPresent()) {
            Message message = messageOptional.get();
            Reply reply = new Reply();
            reply.setMessage(message);
            reply.setContent(replyDTO.getContent());
            reply.setTeacherId(replyDTO.getTeacherId());
            reply.setStudentId(message.getStudentId());
            reply.setTeacherName(replyDTO.getTeacherName());
            Reply savedReply = replyService.saveReply(reply);
            message.setRead(true);
            messageService.save(message);
            return ResponseEntity.ok(convertToDTO(savedReply));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 标记指定消息为已读
    @PostMapping("/{messageId}/markAsRead")
    public ResponseEntity<Void> markMessageAsRead(@PathVariable Long messageId) {
        messageService.markAsRead(messageId);
        return ResponseEntity.ok().build();
    }

    // 点赞指定消息
    @PostMapping("/{messageId}/like")
    public ResponseEntity<Void> likeMessage(@PathVariable Long messageId, @RequestHeader("Authorization") String token) {
        UUID currentTeacherId = getCurrentTeacherId(token);

        if (messageLikeRepository.existsByMessageIdAndTeacherId(messageId, currentTeacherId)) {
            return ResponseEntity.badRequest().build();
        }

        // 创建一个临时的 Reply 对象来传递 teacherId
        Reply tempReply = new Reply();
        tempReply.setTeacherId(currentTeacherId);

        MessageLike like = new MessageLike(tempReply);
        like.setId(UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE);
        like.setMessageId(messageId);
        messageLikeRepository.save(like);

        Message message = messageService.findById(messageId).orElseThrow();
        message.setLikes(message.getLikes() + 1);
        message.setLikedByCurrentTeacher(true);
        messageService.save(message);

        return ResponseEntity.ok().build();
    }

    // 删除指定消息
    @DeleteMapping("/{messageId}")
    public ResponseEntity<Void> deleteMessage(@PathVariable Long messageId, @RequestHeader("Authorization") String token) {
        UUID currentTeacherId = getCurrentTeacherId(token);

        Optional<Message> messageOptional = messageService.findById(messageId);
        if (messageOptional.isPresent()) {
            Message message = messageOptional.get();

            // 检查是否是教师
            if (!message.getTeacherId().equals(currentTeacherId) && !isTeacher()) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }

            messageService.deleteMessage(messageId);
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.notFound().build();
    }


    private boolean isTeacher() {
        try {

            // 获取用户详细信息，明确类型转换为 CustomUserDetails
            CustomUserDetails userDetails = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

            // 检查用户角色是否包含教师角色
            return userDetails != null && userDetails.hasRole("ROLE_TEACHER");
        } catch (Exception e) {
            // 处理解析错误
            return false;
        }
    }

    // 删除指定消息的指定回复
    @DeleteMapping("/{messageId}/replies/{replyId}")
    public ResponseEntity<Void> deleteReply(
            @PathVariable Long messageId,
            @PathVariable Long replyId,
            @RequestHeader("Authorization") String token) {

        UUID currentTeacherId = getCurrentTeacherId(token);
        Optional<Reply> replyOptional = replyService.findById(replyId);

        if (replyOptional.isPresent()) {
            Reply reply = replyOptional.get();

            // 检查是否是回复作者
            if (!reply.getTeacherId().equals(currentTeacherId)) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }

            // 检查是否在2分钟内
            if (ChronoUnit.MINUTES.between(reply.getCreatedAt(), LocalDateTime.now()) > 2) {
                return ResponseEntity.badRequest().build();
            }

            replyService.deleteReply(replyId);
            return ResponseEntity.ok().build();
        }


        return ResponseEntity.notFound().build();

    }

    // 从 token 中获取当前教师 ID
    private UUID getCurrentTeacherId(String token) {
        // 实现从 token 中获取当前教师 ID 的逻辑
        return UUID.randomUUID();
    }

    // 将 Message 转换为 MessageDTO
    private MessageDTO convertToDTO(Message message) {
        MessageDTO messageDTO = new MessageDTO();
        messageDTO.setId(message.getId());
        messageDTO.setContent(message.getContent());
        messageDTO.setCreatedAt(message.getCreatedAt());
        messageDTO.setStudentId(message.getStudentId());
        messageDTO.setLikes(message.getLikes() != null ? message.getLikes() : 0); // 处理 likes 为空的情况
        messageDTO.setTeacherId(message.getTeacherId());
        messageDTO.setRead(message.isRead());
        messageDTO.setLikedByCurrentTeacher(message.isLikedByCurrentTeacher());
        messageDTO.setReplies(message.getReplies() != null
                ? message.getReplies().stream().map(this::convertToDTO).collect(Collectors.toList())
                : new ArrayList<>()); // 确保 replies 是一个数组并转换为 ReplyDTO
        return messageDTO;
    }

    // 将 Reply 转换为 ReplyDTO
    private ReplyDTO convertToDTO(Reply reply) {
        ReplyDTO replyDTO = new ReplyDTO();
        replyDTO.setId(reply.getId());
        replyDTO.setContent(reply.getContent());
        replyDTO.setCreatedAt(reply.getCreatedAt());
        replyDTO.setTeacherId(reply.getTeacherId());
        replyDTO.setStudentId(reply.getStudentId());
        replyDTO.setTeacherName(reply.getTeacherName());
        return replyDTO;
    }
}